package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
)

var HomeContent = new(homeContentService)

type homeContentService struct{}

func (s *homeContentService) List(c *gin.Context, req *model.ReqList) (*[]tables.HomeContent, int64, error) {
	account, err := Request.Account(c)
	if err != nil {
		return nil, 0, err
	}
	where := fmt.Sprintf("acid=%d", account.Id)
	var m []tables.HomeContent
	count, err := tableCommon.QueryListWithPageV2(where, req.PageNo, req.PageSize).OrderBy("id desc").
		FindAndCount(&m)
	if err != nil {
		return nil, 0, err
	}
	return &m, count, nil
}
func (s *homeContentService) Save(c *gin.Context, req *tables.HomeContent) error {
	account, err := Request.Account(c)
	if err != nil {
		return err
	}
	// menu_id是否存在
	get, err := orm.Db.Where("id=?", req.MenuId).Get(&tables.HomeMenu{})
	if err != nil {
		return err
	}
	if !get {
		return errors.New("值错误【menu_id】")
	}

	req.Acid = account.Id
	if req.Id == 0 {
		insert, err := orm.Db.Insert(req)
		if err != nil {
			return err
		}
		if insert == 0 {
			return fmt.Errorf("保存失败")
		}
	} else {
		_, err = orm.Db.Where("id=?", req.Id).Update(req)
		if err != nil {
			return err
		}
	}
	return nil
}
func (s *homeContentService) Delete(c *gin.Context, req *model.ReqId) error {
	user, err := Request.Account(c)
	if err != nil {
		return err
	}
	_, err = orm.Db.ID(req.Id).Where("acid=?", user.Id).Delete(&tables.HomeContent{})
	return err
}
func (s *homeContentService) Info(c *gin.Context, where string, field string) (*tables.HomeContent, error) {
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	var m tables.HomeContent
	get, err := orm.Db.Where(where).Where("acid=?", user.Acid).Cols(field).Get(&m)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取数据不存在")
	}
	return &m, nil
}
